package com.eeepay.eeepay_v2.util;

import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.EditText;

import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author xuqingfeng77
 * @date 2013-11-5
 * @function 检测银行卡 ，身份证,银行卡44分割，手机号、银行卡带星
 */
public class CardTools {

	/*
	 * 11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",
	 * 21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",
	 * 33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",
	 * 42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",
	 * 51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",
	 * 63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"
	 */
	private String[] vcity = new String[] { "11", "12", "13", "14", "15", "21", "22", "23", "31", "32", "33", "34", "35", "36", "37", "41",
			"42", "43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62", "63", "64", "65", "71", "81", "82", "91" };

	public static CardTools mCardTools;

	public static CardTools getInstance() {
		if (mCardTools == null) {
			mCardTools = new CardTools();
		}
		return mCardTools;
	}

	/**
	 * 身份证校验
	 * 
	 * @param card
	 * @return true为假，false为真
	 */
	public boolean checkCard(String card) {
		// 是否为空
		if (TextUtils.isEmpty(card)) {
			return true;
		}
		// 校验长度，类型
		if (!isCard(card)) {
			return true;
		}
		// 检查省份
		if (!checkProvince(card)) {
			return true;
		}
		// 校验生日
		if (!checkBirthday(card)) {
			return true;
		}
		// 检验位的检测
		// if(!checkParity(card))
		// {
		// return true;
		// }
		return false;
	}

	/**
	 * //检查号码是否符合规范，包括长度，类型
	 * 
	 * @param card
	 * @return
	 */
	private boolean isCard(String card) {
		boolean isCard = false;
		// 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
		String checkExpressions = "^[1-9]([0-9]{14}|[0-9]{17}|[0-9]{16}[Xx])$";
		if (card == null) {
			isCard = false;
		} else {
			isCard = Pattern.matches(checkExpressions, card);
		}
		return isCard;
	}

	/**
	 * //取身份证前两位,校验省份
	 * 
	 * @param card
	 * @return
	 */
	private boolean checkProvince(String card) {
		String province = card.substring(0, 2);
		for (String code : vcity) {
			if (province.equals(code)) {
				return true;
			}
		}

		return false;
	}

	/**
	 * 
	 * @param card
	 * @return
	 */
	private boolean checkBirthday(String card) {
		int temYear = Calendar.getInstance().get(Calendar.YEAR);
		int temMonth = Calendar.getInstance().get(Calendar.MONTH) + 1;
		int temDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
		int len = card.length();
		// 身份证15位时，次序为省（3位）市（3位）年（2位）月（2位）日（2位）校验位（3位），皆为数字
		if (len == 15) {

			String year = card.substring(6, 8);
			String month = card.substring(8, 10);
			String day = card.substring(10, 12);
			int tempY = temYear - Integer.parseInt("19" + year);
			if (tempY >= 3 && tempY <= 100) {
				return true;
			}

		}
		// 身份证18位时，次序为省（3位）市（3位）年（4位）月（2位）日（2位）校验位（4位），校验位末尾可能为X
		if (len == 18) {

			String year = card.substring(6, 10);
			String month = card.substring(10, 12);
			String day = card.substring(12, 14);
			int tempY = temYear - Integer.parseInt(year);
			if (tempY >= 3 && tempY <= 150) {
				return true;
			}

		}

		return false;
	}

	/**
	 * 
	 * @param year
	 * @param month
	 * @param day
	 * @param birthday
	 * @return
	 */
	private boolean verifyBirthday(String year, String month, String day, String birthday) {

		// var now_year = now.getFullYear();
		// // 年月日是否合理
		// if (birthday.getFullYear() == year
		// && (birthday.getMonth() + 1) == month
		// && birthday.getDate() == day) {
		// // 判断年份的范围（3岁到100岁之间)
		// var time = now_year - year;
		// if (time >= 3 && time <= 100) {
		// return true;
		// }
		// return false;
		// }
		// return false;
		return false;
	}

	// 校验位的检测、
	/**
	 * 
	 * @param card
	 * @return
	 */
	private boolean checkParity(String card) {
		String card2 = changeFivteen2Eighteen(card);

		int len = card2.length();
		if (len == 18) {
			int[] arrInt = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
			String[] arrCh = new String[] { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" };
			int cardTemp = 0, i;
			String valnum;
			for (i = 0; i < 17; i++) {
				cardTemp += Integer.parseInt(card.substring(i, 1)) * arrInt[i];
			}
			valnum = arrCh[cardTemp % 11];
			if (valnum == card.substring(17, 1)) {
				return true;
			}
			return false;
		}
		return false;
	}

	// 15位转18位身份证号
	private String changeFivteen2Eighteen(String card) {
		if (card.length() == 15) {
			int[] arrInt = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
			String[] arrCh = new String[] { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" };
			int cardTemp = 0;
			card = card.substring(0, 6) + "19" + card.substring(6, card.length() - 6);
			for (int i = 0; i < 17; i++) {
				cardTemp += Integer.parseInt(card.substring(i, 1)) * arrInt[i];
			}
			card += arrCh[cardTemp % 11];
			return card;
		}
		return card;
	}

	/**
	 * 检测银行卡规则// 16 位卡号校验位采用 Luhm 校验方法计算：
	 * 
	 * 1，将未带校验位的 15 位卡号从右依次编号 1 到 15，位于奇数位号上的数字乘以 2 2，将奇位乘积的个十位全部相加，再加上所有偶数位上的数字
	 * 3，将加法和加上校验位能被 10 整除。
	 * 
	 * @param cardno
	 * @return
	 */
	public static boolean isBankCardNo(String cardno) {
		if (TextUtils.isEmpty(cardno)) {
			return false;
		} else if (cardno.length() == 16) {
			char bit = getBankCardCheckCode(cardno.substring(0, cardno.length() - 1));
			return cardno.charAt(cardno.length() - 1) == bit;
		} else if (cardno.length() > 13) {// 存在卡号14位的，19位
			return true;
		}
		return false;

	}

	/**
	 * 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位
	 * 
	 * @param nonCheckCodeCardId
	 * @return
	 */
	public static char getBankCardCheckCode(String nonCheckCodeCardId) {
		if (nonCheckCodeCardId == null || nonCheckCodeCardId.trim().length() == 0 || !nonCheckCodeCardId.matches("\\d+")) {
			throw new IllegalArgumentException("Bank card code must be number!");
		}
		char[] chs = nonCheckCodeCardId.trim().toCharArray();
		int luhmSum = 0;
		for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
			int k = chs[i] - '0';
			if (j % 2 == 0) {
				k *= 2;
				k = k / 10 + k % 10;
			}
			luhmSum += k;
		}
		return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
	}

	/**
	 * 银行卡四位加空格 控制输入卡号监听 控制输入形式为形式6222 4533 2344 2233;
	 * 
	 * @param mEditText
	 */
	public static void bankCardNumAddSpace(final EditText mEditText) {
		mEditText.addTextChangedListener(new TextWatcher() {
			int beforeTextLength = 0;
			int onTextLength = 0;
			boolean isChanged = false;

			int location = 0;// 记录光标的位置
			private char[] tempChar;
			private StringBuffer buffer = new StringBuffer();
			int konggeNumberB = 0;

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				beforeTextLength = s.length();
				if (buffer.length() > 0) {
					buffer.delete(0, buffer.length());
				}
				konggeNumberB = 0;
				for (int i = 0; i < s.length(); i++) {
					if (s.charAt(i) == ' ') {
						konggeNumberB++;
					}
				}
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				onTextLength = s.length();
				buffer.append(s.toString());
				if (onTextLength == beforeTextLength || onTextLength <= 3 || isChanged) {
					isChanged = false;
					return;
				}
				isChanged = true;
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (isChanged) {
					location = mEditText.getSelectionEnd();
					int index = 0;
					while (index < buffer.length()) {
						if (buffer.charAt(index) == ' ') {
							buffer.deleteCharAt(index);
						} else {
							index++;
						}
					}

					index = 0;
					int konggeNumberC = 0;
					while (index < buffer.length()) {
						if ((index == 4 || index == 9 || index == 14 || index == 19 || index == 24 || index == 29)) {
							buffer.insert(index, ' ');
							konggeNumberC++;
						}
						index++;
					}

					if (konggeNumberC > konggeNumberB) {
						location += (konggeNumberC - konggeNumberB);
					}

					tempChar = new char[buffer.length()];
					buffer.getChars(0, buffer.length(), tempChar, 0);
					String str = buffer.toString();
					if (location > str.length()) {
						location = str.length();
					} else if (location < 0) {
						location = 0;
					}

					mEditText.setText(str);
					// mEditText.setSelection(location);
					Editable etable = mEditText.getText();
					Selection.setSelection(etable, location);
					isChanged = false;
				}
			}
		});
	}

	/**
	 * 分割卡号
	 * 
	 * @param str
	 * @return 例如：6222 4332 4333 2222 888
	 */
	public static String split4CardNum(String str) {
		String temp = "";
		if (TextUtils.isEmpty(str))
			return "";
		int lenght = str.length();
		int num = lenght / 4;// 循环多少次
		int yushu = lenght % 4;// 余数
		for (int i = 0; i < num; i++) {
			temp += str.substring(i * 4, (i + 1) * 4) + " ";
		}
		if (yushu > 0) {
			temp += str.substring(4 * num);
		}

		return temp;

	}

	/**
	 * 隐藏银行卡部分数字 显示前6后四
	 * 
	 * @param str
	 * @return 例如：622233******8888
	 */
	public static String hideCardNumWithStar(String str) {
		if (TextUtils.isEmpty(str)) {
			return "";
		}
		if (str.length() < 14) {
			return "未知卡号";
		}
		String temp1 = str.substring(0, 6);
		String temp2 = str.substring(str.length() - 4, str.length());
		return temp1 + "******" + temp2;
	}

	// 手机号规则验证，true验证成功，false验证失败
	public static boolean mobile(String number) {
		if (TextUtils.isEmpty(number)) {
			return false;
		}
		String regularExpression = "^[1][3-8]+\\d{9}";
		return number.matches(regularExpression);
	}

	/**
	 * 隐藏银行卡部分数字 显示前3后四
	 * 
	 * @param str
	 * @return 例如：133****3902
	 */
	public static String hidePhoneNumWithStar(String str) {
		if (TextUtils.isEmpty(str)) {
			return "";
		}
		if (str.length() < 11) {
			return "未知手机号";
		}
		String temp1 = str.substring(0, 3);
		String temp2 = str.substring(str.length() - 4, str.length());
		return temp1 + "****" + temp2;
	}

	/**
	 * 替换换行，回车，空格符
	 * 
	 * @param str
	 * @return
	 */
	public static String replaceBlank(String str) {

		String dest = "";

		if (str != null) {

			Pattern p = Pattern.compile("\\s*|\t|\r|\n");

			Matcher m = p.matcher(str);

			dest = m.replaceAll("");

		}

		return dest;

	}

	/**
	 * 从通讯录中拿到手机号码后进行处理 去掉(+86)
	 * 
	 * @param num
	 * @return
	 */
	public static String phoneNumDispose(String num) {
		String phoneNum = "";
		if (TextUtils.isEmpty(num)) {
			return phoneNum;
		}
		// 判断手机号码mChargePhoneNo
		String str1 = num.substring(0, 3);
		if ("+86".equals(str1)) {// 如果号码带有+86截取
			phoneNum = num.substring(3);
		} else {
			phoneNum = num;
		}
		return phoneNum;
	}
	
//	public static int getBankIconId(String bankName) {
//		if (bankName == null) {
//			return R.drawable.yh_null;
//		} else if (bankName.contains("浙商")) {
//			return R.drawable.yh__0000_zsyh;
//		} else if (bankName.contains("盛京")) {
//			return R.drawable.yh__0001_sjyh;
//		} else if (bankName.contains("宁波银行")) {
//			return R.drawable.yh__0002_nbyh;
//		} else if (bankName.contains("大连银行")) {
//			return R.drawable.yh__0003_dlyh;
//		} else if (bankName.contains("上海银行")) {
//			return R.drawable.yh__0004_shyh;
//		} else if (bankName.contains("农业发展")) {
//			return R.drawable.yh__0005_zgnyfzyh;
//		} else if (bankName.contains("中国人民")) {
//			return R.drawable.yh__0006_zgrmyh;
//		} else if (bankName.contains("兴业")) {
//			return R.drawable.yh__0007_xyyh;
//		} else if (bankName.contains("民生")) {
//			return R.drawable.yh__0008_zgmsyh;
//		} else if (bankName.contains("北京银行")) {
//			return R.drawable.yh__0009_bjyh;
//		} else if (bankName.contains("中信")) {
//			return R.drawable.yh__0010_zxsyyh;
//		} else if (bankName.contains("光大")) {
//			return R.drawable.yh__0011_zggdyh;
//		} else if (bankName.contains("广东发展")) {
//			return R.drawable.yh__0012_gdfzyh;
//		} else if (bankName.contains("浦东发展")||bankName.contains("浦发")) {
//			return R.drawable.yh__0013_shpdfzyh;
//		} else if (bankName.contains("华夏")) {
//			return R.drawable.yh__0014_hxyh;
//		} else if (bankName.contains("深圳发展")) {
//			return R.drawable.yh__0015_szfzyh;
//		} else if (bankName.contains("交通")) {
//			return R.drawable.yh__0016_jtyh;
//		} else if (bankName.contains("广州市商业银行")) {
//			return R.drawable.yh__0017_gzssyyh;
//		} else if (bankName.contains("邮政")) {
//			return R.drawable.yh__0018_zgyz;
//		} else if (bankName.contains("建设")) {
//			return R.drawable.yh__0019_zgjsyh;
//		} else if (bankName.contains("工商")) {
//			return R.drawable.yh__0020_zggsyh;
//		} else if (bankName.contains("招商")) {
//			return R.drawable.yh__0021_zsyh;
//		} else if (bankName.contains("中国银行")) {
//			return R.drawable.yh__0022_zgyh;
//		} else if (bankName.contains("农业")) {
//			return R.drawable.yh__0023_zgnyyh;
//		} else if (bankName.contains("农村") || bankName.contains("农信")) {
//			return R.drawable.yh__0024_gzsncxyhzs;
//		} else if (bankName.contains("平安")) {
//			return R.drawable.yh__0025_payh;
//		} else if (bankName.contains("厦门")) {
//			return R.drawable.yh__0026_xmyh;
//		} else if (bankName.contains("广发")) {
//			return R.drawable.yh__0027_gfyh;
//		} else if (bankName.contains("东莞银行")) {
//			return R.drawable.yh__0028_dgyh;
//		} else if (bankName.contains("杭州银行")) {
//			return R.drawable.yh__0029_hzyh;
//		} else if (bankName.contains("江苏银行")) {
//			return R.drawable.yh__0030_jsyh;
//		} else if (bankName.contains("深圳农村商业银行")) {
//			return R.drawable.yh__0031_szrsyh;
//		}
//
//		return R.drawable.yh_null;
//
//	}
}
